package com.j.lemon.learn.jwt;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.nimbusds.jose.jwk.JWK;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwsHeader;
import io.jsonwebtoken.Jwts;
import org.jose4j.jwk.RsaJsonWebKey;
import org.jose4j.lang.JoseException;

import java.security.interfaces.RSAPublicKey;
import java.text.ParseException;

/**
 * @author lijunjun
 * @title: JWTUtil
 * @description: TODO
 * @date 2023/4/616:58
 */
public class JWTUtil {

    public static void main(String[] args) throws ParseException, JoseException {
        String jwks = "{\"kty\":\"RSA\",\"e\":\"AQAB\",\"kid\":\"df8e597e-3aa0-437e-90bf-d6b13df98931\",\"n\":\"z8i9POs68G86G5YpBSxf-AevNHq2tKo6oTLsq_oklNM9wWph2bW6GCAr_xCvOBeUMX9ulst5P7VDE7YsOE_nT-ewdoh-7h4jPkG7Re9rU0YFXTkuBKTKy9IXlz6ye_An8XRvj__AooSKxDLsfhR6XRAkhuCzRqWIRadpuGn43Y5x0gvW5cSd9AvuOJRsip4Q8vkKsEj1njXNNy9BFUN9YPgO1g8hffXuI92l_qxCvGRqRVrrDhNlo3PpzvztYp0cu6wUBc95ITrYsBS73z5ylVfVLxkUWiTccGPCUEyASJ2eVV8KNwpWyBruTyzkqcn7D_UFfYcfKy5Ll3xlwVaEIQ\"}";
        //生成密钥
        JSONObject readJSONObject = JSONUtil.parseObj(jwks);
        RsaJsonWebKey pub = new RsaJsonWebKey(readJSONObject);
        //获取公钥
        RSAPublicKey rsaPublicKey = pub.getRsaPublicKey();

        // 生成的token
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImV4cCI6MTY2MzI5NzQzMX0.Ju5EzKBpUnuIRhDG1SU0NwMGsd9Jl_8YBcMM6PB2C20";
        // 解析head信息
//        JwsHeader jwsHeader = Jwts
//                .parser()
//                .setSigningKey(rsaPublicKey)
//                .parseClaimsJws(token)
//                .getHeader();
//
//        System.out.println(jwsHeader); // {typ=JWT, alg=HS256}
//        System.out.println("typ:"+jwsHeader.get("typ"));

//        // 解析Payload
//        Claims claims =    Jwts
//                .parser()
//                .setSigningKey("secret")
//                .parseClaimsJws(token)
//                .getBody();
//        System.out.println(claims);// {sub=1234567890, name=John Doe, admin=true, exp=1663297431}
//        System.out.println("admin:"+claims.get("admin"));
//
        // 解析Signature
        String signature =    Jwts
                .parser()
                .setSigningKey(rsaPublicKey)
                .parseClaimsJws(token)
                .getSignature();
        System.out.println(signature); // Ju5EzKBpUnuIRhDG1SU0NwMGsd9Jl_8YBcMM6PB2C20
    }
}
